import { createRouter, createWebHashHistory } from 'vue-router'
import Home from '../views/Home.vue'
import PlayerList from '../views/player/index.vue'
import { useUserStore } from '../stores/user'

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home
  },
  {
    path: '/player',
    name: 'Player',
    component: PlayerList
  },
  {
    path: '/competition',
    name: 'Competition',
    component: () => import('../views/competition/index.vue')
  },
  {
    path: '/competition/grouping',
    name: 'Grouping',
    component: () => import('../views/competition/GroupingPage.vue')
  },
  {
    path: '/teams',
    name: 'Teams',
    component: () => import('../views/teams/index.vue')
  },
  {
    path: '/statistics',
    name: 'Statistics',
    component: () => import('../views/statistics/index.vue')
  },
  {
    path: '/settings',
    name: 'Settings',
    component: () => import('../views/settings/index.vue')
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/login.vue')
  }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})

router.beforeEach((to, _from, next) => {
  const userStore = useUserStore()
  const isLoggedIn = !!userStore.userInfo
  // 允许未登录访问的页面
  const publicPages = ['/login', '/competition/grouping']
  if (!isLoggedIn && !publicPages.includes(to.path)) {
    next('/login')
  } else if (isLoggedIn && to.path === '/login') {
    next('/')
  } else {
    next()
  }
})

export default router
